<template>
  <div class="rule-container">
    <div class="create-container">
      <el-button type="primary" @click="dialogVisible=true">增加停车计费规则</el-button>
      <el-button @click="exportToExcel">导出Excel</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table :data="ruleList" style="width: 100%">
        <el-table-column type="index" label="序号" :index="indexMethod" />
        <el-table-column label="计费规则编号" prop="ruleNumber" />
        <el-table-column label="计费规则名称" prop="ruleName" />
        <el-table-column label="免费时长(分钟)" prop="freeDuration" />
        <el-table-column label="收费上线(元)" prop="chargeCeiling" />
        <el-table-column label="计费方式">
          <template #default="scope">
            {{ formatChargeType(scope.row.chargeType) }}
          </template>
        </el-table-column>
        <el-table-column label="计费规则" prop="ruleNameView" />
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="scope">
            <el-button size="mini" type="text">编辑</el-button>
            <el-button size="mini" type="text" @click="deleteRule(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :page-size="params.pageSize"
        :current-page="params.page"
        layout="prev, pager, next"
        :total="total"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 弹框 -->
    <rule-upload :dialog-visible.sync="dialogVisible" @getRuleList="getRuleList" />
  </div>
</template>

<script>
import { getRuleListAPI, deleteRuleAPI } from '@/api/Car/carRule'
import { utils, writeFileXLSX } from 'xlsx'
import ruleUpload from './components/ruleUpload.vue'
export default {
  name: 'Building',
  components: {
    ruleUpload
  },
  data() {
    return {
      ruleList: [],
      params: {
        page: 1,
        pageSize: 2
      },
      total: 0,
      dialogVisible: false // 控制弹框关闭打开
    }
  },
  watch: {
    /**
      * 根据不同的收费类型清除表单中相应字段的验证状态
      * 此函数在用户选择不同的收费模式时调用，目的是清除不适用于当前收费模式的表单字段的验证状态
      * * @param {String} val - 选择的收费类型标识符，可以是'turn'（按次计费）、'duration'（按时计费）或'partition'（分段计费）
    */
    'addForm.chargeType'(val) {
      // 当选择按次计费时，清除与时间相关的字段验证
      if (val === 'turn') {
        this.$refs.addForm.clearValidate(['durationTime', 'durationPrice', 'partitionFrameTime', 'partitionFramePrice', 'partitionIncreaseTime', 'partitionIncreasePrice'])
        // 当选择按时计费时，清除与按次和分段相关的字段验证
      } else if (val === 'duration') {
        this.$refs.addForm.clearValidate(['turnPrice', 'partitionFrameTime', 'partitionFramePrice', 'partitionIncreaseTime', 'partitionIncreasePrice'])
        // 当选择分段计费时，清除与按次和按时相关的字段验证
      } else if (val === 'partition') {
        this.$refs.addForm.clearValidate(['turnPrice', 'durationTime', 'durationPrice'])
      }
    }
  },
  mounted() {
    this.getRuleList()
  },
  methods: {
    async getRuleList() {
      const res = await getRuleListAPI(this.params)
      this.ruleList = res.data.rows
      this.total = res.data.total
    },
    // 删除规则
    deleteRule(id) {
      this.$confirm('此操作将删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await deleteRuleAPI(id)
        this.$message.success('删除计费规则成功')
        this.getRuleList()
      })
    },
    // 导出表格
    async exportToExcel() {
      const res = await getRuleListAPI(this.params)
      // 表头英文字段key
      const tableHeaderKeys = ['ruleNumber', 'ruleName', 'freeDuration', 'chargeCeiling', 'chargeType', 'ruleNameView']
      const list = res.data.rows.map(item => {
        const obj = {}
        tableHeaderKeys.forEach(key => {
          obj[key] = item[key]
        })
        return obj
      })
      // 表头中文字段value
      const tableHeaderValues = ['计费规则编号', '计费规则名称', '免费时长(分钟)', '收费上线(元)', '计费方式', '计费规则']
      // 创建一个新的工作簿
      const workbook = utils.book_new()
      // 创建一个工作表 要求一个对象数组格式
      const worksheet = utils.json_to_sheet(list)
      // 把工作表添加到工作簿  Data为工作表名称
      utils.book_append_sheet(workbook, worksheet, 'Data')
      // 改写表头
      utils.sheet_add_aoa(worksheet, [tableHeaderValues], { origin: 'A1' })
      // 导出方法进行导出
      writeFileXLSX(workbook, 'SheetJSVueAoO.xlsx')
    },
    // 适配收费状态
    formatChargeType(type) {
      const TYPEMAP = {
        'duration': '按时长收费',
        'turn': '按次收费',
        'partition': '分段收费'
      }
      return TYPEMAP[type]
    },
    // 点击页码
    handleCurrentChange(val) {
      this.params.page = val
      this.getRuleList()
    },
    indexMethod(index) {
      return (this.params.page - 1) * this.params.pageSize + index + 1
    }
  }
}
</script>

<style lang="scss" scoped>
.rule-container {
  padding: 20px;
  background-color: #fff;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container{
  margin: 10px 0px;
}
.page-container{
  padding:4px 0px;
  text-align: right;
}
.form-container{
  padding:0px 80px;
}
</style>
